package com.dili.dd.gpi.util;

import com.dili.dd.gpi.exception.BusinessException;

public class DbTypeUtils {

	public static DataBaseType getDbTypeByUrl(String url) {

		if (url.contains("mysql")) {
			return DataBaseType.MYSQL;
		} else if (url.contains("hive2")) {
			return DataBaseType.HIVE;
		} else if (url.contains("hbase")) {
			return DataBaseType.HBASE;
		} else if (url.contains("maria")) {
			return DataBaseType.MARIADB;
		} else if (url.matches("jdbc:(microsoft:)?sqlserver://.*")) {
			return DataBaseType.SQL_SERVER;
		} else if(url.matches("jdbc:postgresql://.*")){
            return DataBaseType.POSTGRESQL;
        }else{
            return DataBaseType.UNKNOW;
        }
	}

    /**
     * 从数据库连接中分离出url
     * @param url
     * @return
     */
    public static String getURI(String url){
        DataBaseType type = getDbTypeByUrl(url);
        switch (type){
            case HIVE:
            case POSTGRESQL:
            case MYSQL:
            case MARIADB:
                return url.substring(0,url.lastIndexOf("/"));
            case SQL_SERVER:
                return url.substring(0,url.indexOf(";"));
            case HBASE:
                return url;
            default: return url;
        }
    }

    /**
     * 从数据库连接中分离出数据库明
     * @param url
     * @return
     */
    public static String getDB(String url) throws BusinessException {
        DataBaseType type = getDbTypeByUrl(url);
        switch (type){
            case HIVE:
            case POSTGRESQL:
            case MYSQL:
            case MARIADB:
                String sub =  url.substring(url.lastIndexOf("/") + 1);
                String[] split = sub.split("\\?");
                return split[0];
            case SQL_SERVER:
                sub = url.substring(url.indexOf(";") + 1);
                String[] split1 = sub.split(";");
                for (String s : split1) {
                    if(s.contains("DatabaseName")){
                        return s.split("=")[1].trim();
                    }
                }
                throw new BusinessException("错误的数据库url");
            case HBASE:
                return null;
            default: return null;
        }
    }
}
